package com.lulalei.dbviewer.commons.factory.GenerateBeanFactory;

import com.lulalei.dbviewer.commons.bean.GenerateBean;
import com.lulalei.dbviewer.commons.exception.CustomizeException;
import com.lulalei.dbviewer.commons.utils.PomReaderUtils;
import com.lulalei.dbviewer.commons.utils.ProjectPathUtils;
import com.lulalei.dbviewer.dto.GenerateDTO;
import com.lulalei.dbviewer.strategy.DBStrategyManager;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 代码生成在引用的模块下面，相关属性
 */
@Component
public class OwnModuleGenerateBeanFactory extends AbstractGenerateBeanFactory{

    public OwnModuleGenerateBeanFactory(DBStrategyManager dbManager) {
        super(dbManager);
    }


    @Override
    public GenerateBean createGenerateBean(GenerateDTO generateDTO) throws CustomizeException {
        GenerateBean generateBean = new GenerateBean();

        //获取路径的相关信息
        try {
            generateBean.setModuleQualifiedName(moduleQualifiedName(null));
            generateBean.setJavaCodeDir(ProjectPathUtils.getOwnModulePackageDir());
            generateBean.setXmlDir(ProjectPathUtils.buildPath(ProjectPathUtils.getOwnModuleResourcesDir() + "mapper") + File.separator);
        } catch (XmlPullParserException | IOException e) {
            throw new CustomizeException("pom.xml读取失败,无法获取相关路径");
        }

        try {
            generateBean.setTables(getTableAndField(generateDTO));
        } catch (SQLException e) {
            e.printStackTrace();
            throw new CustomizeException("查询表信息失败,请检查连接");
        }
        return generateBean;
    }


    @Override
    public String moduleQualifiedName(String moduleName) throws XmlPullParserException, IOException, CustomizeException {
        String rootGroupId = PomReaderUtils.getGroupId();
        String rootArtifactId = PomReaderUtils.getArtifactId(PomReaderUtils.getCurrentPomModel());
        return rootGroupId + "." + rootArtifactId.replace("-",".");
    }
}
